package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;


@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 上传图片
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        if(multipartFile == null || multipartFile.getSize() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"请选择文件");
        }
        //2.调用minio上传图片(先要集成minio，才能注入FileStorageService)
        // (参考heima-leadnews-test里的例子，先在pom.xml中引入heima-file-starter模块，然后在bootstrap.yml里引入minio的相关配置（在nacos里配置）)
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //获取上传文件的原始名称
        String originalFilename = multipartFile.getOriginalFilename();
        // 截取后缀 123.jpg
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String fileId = null;
        try {
            fileId = fileStorageService
                    .uploadImgFile("", fileName + postfix, multipartFile.getInputStream());
            log.info("上传文件成功，fileId:{}",fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl-上传文件失败");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"上传失败");
        }
        //3.保存图片信息到mysql
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short) 0);//默认未收藏
        wmMaterial.setType((short) 0);//0是图片，1是视频
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);

        //4.返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 查询素材列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1. 检查参数
        dto.checkParam();
        // 2. 分页查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //是否收藏 0 未收藏，1 已收藏
        if(dto.getIsCollection() != null && dto.getIsCollection() == 1){
            //是1，则查询已收藏的所有图片
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //是0，则查询所有图片(无论是否收藏)

        //按照用户查询
        lambdaQueryWrapper.eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId());
        // 按照创建时间倒序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        page = page(page,lambdaQueryWrapper);
        //想要让page生效，需要在启动类中添加一个mybatis-plus的插件

        // 3. 返回结果
        PageResponseResult pageResponseResult = new PageResponseResult
                (dto.getPage(), dto.getSize(), (int) page.getTotal());

        pageResponseResult.setData(page.getRecords());

        return pageResponseResult;
    }
}
